package jin.si.com.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import jin.si.com.entity.User;
import jin.si.com.service.impl.UserServiceImpl;
import jin.si.com.utils.JsonData;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @description: 拦截器
 * @ClassName TestInterceptor
 * @Author MT
 * @Date 2021/5/12 11:14
 **/
public class TestInterceptor implements HandlerInterceptor {
    private ObjectMapper objectMapper=new ObjectMapper();

    //执行后端控制器业务逻辑之前执行
    @Override
    public boolean preHandle(HttpServletRequest res, HttpServletResponse resp, Object handler) throws Exception {
        String token = res.getHeader("token");
        if(!StringUtils.isEmpty(token)){
            User user = (User) UserServiceImpl.sessionMap.get(token);
            if(user!=null){
                return true;
            }else{
                JsonData jsonData = JsonData.buildError("登录失效");
                String jsonStr = objectMapper.writeValueAsString(jsonData);
                renderJson(resp,jsonStr);
            }
        }else{
            JsonData jsonData = JsonData.buildError("未登录");
            String jsonStr = objectMapper.writeValueAsString(jsonData);
            renderJson(resp,jsonStr);
        }

        return false;
    }

    //执行后端控制器业务逻辑之后，返回试图之前执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //试图渲染完毕，前端控制器执行完成，进行操作，可以清理资源
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private void renderJson(HttpServletResponse reps,String jsonStr){
        reps.setCharacterEncoding("UTF-8");
        reps.setContentType("application/json");
        try{
            PrintWriter writer=reps.getWriter();
            writer.write(jsonStr);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }


}
